const express = require('express');
const router = express.Router();
const Joi = require('joi');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

router.post('/', async (req,res) =>{
    const {error} = validateUser(req.body);
    if(error){
        return res.status(400).send({'message':error.details[0].message});
    }
    const db = req.app.get('db');
    let user = await db.get('Select * from users where phoneNumber=? And isDisabled=0',
        req.body.phone);
    if (!user) return res.status(400).send({'message':'Invaild phone number or password.'});
    
    const vaildPassword = await bcrypt.compare(req.body.password,user.password);
    if (!vaildPassword) return res.status(400).send({'message':'Invaild phone number or password.'});
    
    const token = jwt.sign({id:user.id, isAdmin: user.isAdmin},'jwtToken');
    
    return res.send({'token':token,'message':'login seccessful'});
});

function validateUser(user){
    const schema = Joi.object({
        phone:Joi.string()
            .regex(new RegExp('^[1][3,4,5,7,8][0-9]{9}$'))
            .required()
            .error(new Joi.ValidationError('Invaild Phone Number', [{message:'Invaild Phone Number'}])),
        password: Joi.string()
            .regex(new RegExp('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$'))
            .required()
            .error(new Joi.ValidationError('Invaild Password', [{message:'Invaild Password'}]))
    });

    return schema.validate(user);
}

module.exports = router;